// https://codepen.io/siouxcitizen/pen/PowVgXK?editors=0010
import { 
  AmbientLight,
  AnimationMixer,
  Clock,
  DirectionalLight,
  GridHelper,
  LoadingManager,
  PerspectiveCamera,
  Scene, 
  WebGLRenderer
} from "three";
import stats from '../../utils/stats';
// 调用
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls';
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader';
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader";
import { GUI } from 'dat.gui';

let clock = new Clock();
let scene = new Scene();
let camera = new PerspectiveCamera(70, window.innerWidth/window.innerHeight, 0.1, 1000);
camera.position.set(0, 20, 40);
camera.lookAt(scene.position);

const renderer = new WebGLRenderer({ antialias: true });
renderer.setPixelRatio(window.devicePixelRatio);
renderer.setSize(window.innerWidth, window.innerHeight);

document.body.appendChild(renderer.domElement);

// 网格辅助
scene.add(new GridHelper(100, 20, 0x888888, 0x444444));
const ambientLight = new AmbientLight(0x85b2cd);
scene.add(ambientLight);
const light = new DirectionalLight(0xc1582d, 1);
light.position.set(0, -70, 100).normalize();
scene.add(light);


let mixer: AnimationMixer
let mesh 

const manager = new LoadingManager();
manager.onProgress = function(item, loaded, total) {};

const loader = new GLTFLoader();
loader.setCrossOrigin( 'anonymous' );
loader.setDRACOLoader(new DRACOLoader());

loader.load(
  '/models/dinosaur/trex_running.gltf',
  gltf => {
    mesh = gltf.scene;
    mesh.scale.set(0.06, 0.06, 0.06);

    let animations = gltf.animations;

    if (animations && animations.length) {
      // https://threejs.org/docs/index.html#api/zh/animation/AnimationMixer
      mixer = new AnimationMixer(mesh);

      for (let i = 0; i < animations.length; i++) {
        let animation = animations[i];
        mixer.clipAction( animation ).play();
      }
    }

    scene.add( mesh );
  },
  xhr => {
    console.log( xhr.loaded / xhr.total * 100 + '% loaded')
  },
  err => {
    console.error(err)
  }
);

const trackballControls = new OrbitControls(camera, renderer.domElement);
trackballControls.target.set(0, 10, 0);

const control = {
  time: 0,
  timeScale: 1
};
const gui = new GUI();
const ani = gui.addFolder('AnimationMixer');
ani.add(control, 'time').name('时间').listen();
ani.add(control, 'timeScale', 0, 3).name('速度').onChange(val => mixer.timeScale = val);
ani.open();

render();

function render() {
  stats.update();
  trackballControls.update();

  if (mixer) {
    // 更新动画
    mixer.update(clock.getDelta());
    control.time = mixer.time;
  }

  requestAnimationFrame(render);
  renderer.render(scene, camera);
}